/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servletsLogin;

import Utils.User;
import Utils.dbManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Alice
 */
@WebServlet(name="Autentica", urlPatterns={"/Autentica"})
public class Autentica extends HttpServlet {
    private dbManager manager;
   
    @Override
public void init() throws ServletException {
// inizializza il DBManager dagli attributi di Application
this.manager = (dbManager)super.getServletContext().getAttribute("dbmanager");
}

 @Override    
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
 
    
 String roles ="";
 String username= req.getParameter("username");
 String password= req.getParameter("password");
 
 User user;

 try{
     user=manager.authenticate(username, password,roles);

     
     } catch (SQLException ex) {
throw new ServletException(ex);
} 

if (user == null) {

   resp.sendRedirect(req.getContextPath() + "/ErrorLoginServlet");

} else {
   
HttpSession session = req.getSession(true);
session.setAttribute("username", username);



// mando un redirect alla servlet che carica i prodotti
roles=user.getRoles();


if(roles.equals("seller")){
session.setAttribute("seller",user);
    resp.sendRedirect(req.getContextPath() + "/SellerLandingServlet");}
else if (roles.equals("buyer")){
        session.setAttribute("buyer",user);
        resp.sendRedirect(req.getContextPath() + "/BuyerLandingServlet");}
}
}
 
 }



   